<template>
  <div class="summary-set" v-loading="loading">
    <fieldset>
      <legend>表参数</legend>
      <el-form :model="form" class="summary-set-w" label-width="120px">
        <el-form-item label="表位" prop="tableVal">
          <el-select v-model="form.tableVal">
            <el-option
              :label="currentData.position"
              :value="currentData.position"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表类型">
          <el-select v-model="form.tableType">
            <el-option :label="currentData.name" :value="currentData.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="波特率">
          <el-select
            v-model="form.baudRate"
            placeholder="please select your zone"
          >
            <el-option label="1200" value="1200" />
            <el-option label="2400" value="2400" />
            <el-option label="4800" value="4800" />
            <el-option label="9600" value="9600" />
            <el-option label="19200" value="19200" />
          </el-select>
        </el-form-item>
        <el-form-item label="校验位">
          <el-select v-model="form.meterCheck">
            <el-option label="无校验" value="1" />
            <el-option label="奇校验" value="2" />
            <el-option label="偶校验" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="通讯规约">
          <el-select v-model="form.communication" placeholder="通讯规约">
            <el-option label="DL/T 6451997" value="1" />
            <el-option label="DL/T 645 2007" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作码">
          <el-input v-model="form.opcode" />
        </el-form-item>
        <el-form-item label="表密码">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item>
          <fieldset class="summary-set-r-w-td">
            <legend>广播:</legend>
            <el-radio-group v-model="form.broadcast">
              <el-radio label="170">AA</el-radio>
              <el-radio style="margin-left: 50px" label="153">99</el-radio>
            </el-radio-group>
          </fieldset>
          <el-button class="ssr-btn" type="primary" @click="onSubmit"
            >设置参数</el-button
          >
        </el-form-item>
        <el-form-item label="表地址">
          <el-input v-model="form.addr" />
        </el-form-item>
        <el-form-item>
          <el-button class="ssr-btn" type="primary" @click="meterRead"
            >读取</el-button
          >
          <el-button class="ssr-btn" type="primary" @click="meterWrite"
            >写入</el-button
          >
        </el-form-item>
      </el-form>
    </fieldset>
    <fieldset style="padding: 0 5px" v-loading="loadingWheel">
      <legend>轮显设置</legend>
      <div class="summary-set-r">
        <div>
          <h5>可选项</h5>
          <div>
            <el-table
              ref="wheelRef"
              border
              class="summary-set-r-w"
              :data="wheelAllData"
              style="width: 100%"
              highlight-current-row
              @row-click="rowAdd"
              @row-dblclick="rowDbAdd"
            >
              <el-table-column prop="id" label="" width="50" />
              <el-table-column prop="msg" label="显示项目" :width="width" />
            </el-table>
          </div>
          <el-button class="mt10" @click="setDefaultData"> 设置默认 </el-button>
        </div>
        <div class="summary-set-r-btn">
          <el-button @click="addWheel"> &gt </el-button>
          <el-button @click="clearWheel"> &lt&lt </el-button>
          <el-button @click="reduceWheel"> &lt </el-button>
        </div>
        <div>
          <h5>已选项</h5>
          <div>
            <el-table
              ref="wheelCheckedRef"
              border
              class="summary-set-r-w"
              :data="wheelData"
              style="width: 100%"
              highlight-current-row
              @row-click="rowReduce"
              @row-dblclick="rowDbReduce"
            >
              <el-table-column type="index" width="50" />
              <el-table-column prop="msg" label="显示项目" :width="width" />
            </el-table>
          </div>
          <div class="ml10 mt10">
            设置类型：<el-select
              v-model="wheelType"
              :style="isWap ? 'width:65px' : 'width:100px'"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button
              :style="isWap ? 'width:80px' : 'width:100px'"
              class="ml10"
              @click="wheelWrite"
            >
              写入
            </el-button>
          </div>
        </div>
        <div class="summary-set-r-btn">
          <el-button @click="handelTop">
            <el-icon><Top /></el-icon>
          </el-button>
          <el-button @click="handelBottom">
            <el-icon><Bottom /></el-icon>
          </el-button>
        </div>
      </div>
    </fieldset>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import { useAppStore } from "@/stores";
import { useWinSize } from "@/utils/comm.js";
const useApp = useAppStore();
let { currentPlanId } = storeToRefs(useApp);
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import {
  wheelDisplayList,
  wheelDisplayCheckedList,
  wheelDisplaySingle,
  wheelDisplaySingleChecked,
} from "@/utils/faultDataList.js";
import {
  meterShowList,
  meterMeterShow,
  commSendInfo,
  meterReadMeterAddr,
  meterWriteMeterAddr,
} from "@/api/source.js";
const props = defineProps({
  currentData: Object,
});
// do not use same name with ref
const form = reactive({
  tableVal: props.currentData.position,
  tableType: props.currentData.name,
  baudRate: "4800",
  meterCheck: "1",
  communication: "1",
  opcode: "",
  password: "",
  broadcast: "153",
  addr: "",
});
const width = ref();
const isWap = ref(false);
const loading = ref(false);
const wheelType = ref("2");
const loadingWheel = ref(false);
const options = [
  {
    value: "1",
    label: "轮显",
  },
  {
    value: "2",
    label: "键显",
  },
];
const wheelData = ref();
const wheelAllData = ref();
const wheelRef = ref();
const wheelCheckedRef = ref();
const currentWheel = ref();
const currentCheckedWheel = ref();
const currentIndex = ref(0);
const currentCheckedIndex = ref();

onMounted(() => {
  watch(
    props,
    (newValue, oldValue) => {
      if (newValue.currentData.type != 2 && newValue.currentData.type != 6) {
        form.baudRate = "2400";
        form.communication = "2";
        form.meterCheck = "3";
      } else {
        form.baudRate = "4800";
        form.communication = "1";
        form.meterCheck = "1";
      }
    },
    { immediate: true },
    { deep: true }
  );
  //获取轮显数据
  getMeterShowList();
  //判断屏幕尺寸
  const size = useWinSize();
  if (size.width > 1440) {
    width.value = 300;
    isWap.value = false;
  } else {
    width.value = 200;
    isWap.value = true;
  }
});

const onSubmit = async () => {
  let parm = {
    meterCheck: form.meterCheck,
    baudRate: form.baudRate,
    pos: props.currentData.position,
  };
  loading.value = true;
  await commSendInfo(parm)
    .then((res) => {
      // console.log(res);
      loading.value = false;
      ElMessage({
        type: "success",
        message: "设置成功",
      });
    })
    .catch((err) => {
      console.log(err);
      loading.value = false;
      ElMessage({
        type: "warning",
        message: "设置失败",
      });
    });
};
//读表地址
const meterRead = async () => {
  let parm = {
    broadcast: form.broadcast,
    pos: props.currentData.position,
    planId: currentPlanId.value,
  };
  loading.value = true;
  await meterReadMeterAddr(parm)
    .then((res) => {
      form.addr = res.data.data;
      // console.log(res);
      loading.value = false;
      ElMessage({
        type: "success",
        message: "读取成功",
      });
    })
    .catch((err) => {
      console.log(err);
      loading.value = false;
      ElMessage({
        type: "warning",
        message: "读取失败",
      });
    });
};
//写表地址
const meterWrite = async () => {
  let parm = {
    addr: form.addr,
    pos: props.currentData.position,
    planId: currentPlanId.value,
  };
  loading.value = true;
  await meterWriteMeterAddr(parm)
    .then((res) => {
      // console.log(res);
      loading.value = false;
      ElMessage({
        type: "success",
        message: "写入成功",
      });
    })
    .catch((err) => {
      console.log(err);
      loading.value = false;
      ElMessage({
        type: "warning",
        message: "写入失败",
      });
    });
};
//获取轮显数据
const getMeterShowList = async () => {
  let parm = {
    pos: props.currentData.position,
    planId: currentPlanId.value,
  };
  if (props.currentData.wiringType === "单相") {
    wheelAllData.value = wheelDisplaySingle;
  } else {
    wheelAllData.value = wheelDisplayList;
  }
  await meterShowList(parm)
    .then((res) => {
      if (res.data.length > 0) {
        wheelData.value = res.data;
        currentIndex.value = 0;
        currentCheckedIndex.value = wheelData.value.length - 1;
        currentWheel.value = wheelAllData.value[currentIndex.value]; //当前可选高亮数据
        wheelRef.value.setCurrentRow(wheelAllData.value[currentIndex.value]); //当前可选数据高亮
        currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value]; //当前可选高亮数据
        wheelCheckedRef.value.setCurrentRow(
          wheelData.value[currentCheckedIndex.value]
        ); //当前可选数据高亮
      } else {
        setDefaultData();
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
//轮显写入
const wheelWrite = async () => {
  loadingWheel.value = true;
  let methodName;
  if (props.currentData.wiringType === "单相") {
    if (wheelType.value === "2") methodName = "SingleKeyShow";
    else methodName = "singleRotator";
  } else {
    if (wheelType.value === "2") methodName = "ThreeKew";
    else methodName = "ThreeRotator";
  }
  let showNum = "";
  wheelData.value.forEach((item, index) => {
    if (showNum) showNum += "," + item.id;
    else showNum = item.id;
  });
  let parm = {
    methodName, //ThreeRotator三相轮显;singleRotator单相轮显;ThreeKew三相键显:SingleKeyShow单相键显
    pos: props.currentData.position,
    planId: currentPlanId.value,
    showNum,
  };
  await meterMeterShow(parm)
    .then((res) => {
      console.log(res);
      loadingWheel.value = false;
      ElMessage({
        type: "success",
        message: "写入成功",
      });
    })
    .catch((err) => {
      console.log(err);
      loadingWheel.value = false;
      ElMessage({
        type: "warning",
        message: "写入失败",
      });
    });
};
//设置默认
const setDefaultData = () => {
  if (props.currentData.wiringType === "单相") {
    wheelData.value = wheelDisplaySingleChecked;
  } else {
    wheelData.value = wheelDisplayCheckedList;
  }
  currentIndex.value = 0;
  currentCheckedIndex.value = wheelData.value.length - 1;
  currentWheel.value = wheelAllData.value[currentIndex.value]; //当前可选高亮数据
  wheelRef.value.setCurrentRow(wheelAllData.value[currentIndex.value]); //当前可选数据高亮
  currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value]; //当前可选高亮数据
  wheelCheckedRef.value.setCurrentRow(
    wheelData.value[currentCheckedIndex.value]
  ); //当前可选数据高亮
};
//增加轮显选中
const addWheel = () => {
  currentWheel.value = wheelAllData.value[currentIndex.value]; //当前可选高亮数据
  let obj = wheelData.value.filter(
    (item1) => item1.id === currentWheel.value.id
  );
  if (!obj.length) wheelData.value.push(currentWheel.value);
  currentCheckedIndex.value = wheelData.value.length - 1;
  currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value];
  wheelCheckedRef.value.setCurrentRow(
    wheelData.value[currentCheckedIndex.value]
  );
  ++currentIndex.value;
  wheelRef.value.setCurrentRow(wheelAllData.value[currentIndex.value]);
};
//减少轮显选中
const reduceWheel = () => {
  let newData = [];
  if (currentCheckedIndex.value >= 0) {
    currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value];
    wheelData.value.forEach((item, index) => {
      if (item.id != currentCheckedWheel.value.id) {
        newData.push(item);
      }
    });
    wheelData.value = newData;
    --currentCheckedIndex.value;
    wheelCheckedRef.value.setCurrentRow(
      wheelData.value[currentCheckedIndex.value]
    );
  }
};
//清除选中
const clearWheel = () => {
  wheelData.value = [];
  currentIndex.value = 0;
  currentCheckedIndex.value = 0;
  wheelRef.value.setCurrentRow(wheelAllData.value[0]);
};
//表格单击
const rowAdd = (row) => {
  wheelAllData.value.forEach((item, index) => {
    if (item.id === row.id) {
      currentIndex.value = index;
      currentWheel.value = item;
    }
  });
};
//表格双击新增
const rowDbAdd = (row) => {
  let newData = [];
  if (!wheelData.value.length) {
    wheelData.value.push(row);
  } else {
    let obj = wheelData.value.filter((item1) => item1.id === row.id);
    if (!obj.length) {
      wheelAllData.value.forEach((item, index) => {
        if (item.id === row.id) {
          wheelData.value.push(item);
        }
      });
    }
  }
};
//表格单击
const rowReduce = (row) => {
  wheelData.value.forEach((item, index) => {
    if (item.id === row.id) {
      currentCheckedIndex.value = index;
      currentCheckedWheel.value = item;
    }
  });
};
//表格双击减少
const rowDbReduce = (row) => {
  let newData = [];
  let indexI = 0;
  wheelData.value.forEach((item, index) => {
    if (item.id != row.id) {
      newData.push(item);
      // delete wheelData.value[index];
    } else {
      indexI = index;
    }
  });
  wheelData.value = newData;
  pregData(indexI);
};
const pregData = (indexI) => {
  console.log(indexI);
  if (indexI <= wheelData.value.length) {
    --indexI;
  } else {
    ++indexI;
  }
  currentCheckedWheel.value = indexI;
  currentCheckedWheel.value = wheelData.value[indexI]; //当前可选高亮数据
  wheelCheckedRef.value.setCurrentRow(wheelData.value[indexI]); //当前可选数据高亮
};
//轮显选中数据向上排序
const handelTop = () => {
  console.log("handelTop", currentCheckedIndex.value, wheelData.value);
  if (wheelData.value.length === 1) {
    currentCheckedWheel.value = wheelData.value[0];
  } else if (currentCheckedIndex.value) {
    currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value];
    --currentCheckedIndex.value;
    wheelCheckedRef.value.setCurrentRow(
      wheelData.value[currentCheckedIndex.value]
    );
  }
};
//轮显选中数据向下排序
const handelBottom = () => {
  console.log("handelBottom", currentCheckedIndex.value);
  if (wheelData.value.length === 1) {
    currentCheckedWheel.value = wheelData.value[0];
  } else if (currentCheckedIndex.value < wheelData.value.length - 1) {
    currentCheckedWheel.value = wheelData.value[currentCheckedIndex.value];
    ++currentCheckedIndex.value;
    wheelCheckedRef.value.setCurrentRow(
      wheelData.value[currentCheckedIndex.value]
    );
  }
};
</script>

<style lang="scss" scoped>
.summary-set {
  display: flex;
  justify-content: space-between;
  .summary-set-r {
    display: flex;
  }
  .summary-set-r-btn {
    // width: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0px 20px;
    margin-top: 10%;
    .el-button {
      margin: 10px 0px;
      width: 50px;
    }
  }
  .el-form {
    .el-form-item {
      margin-bottom: 10px;
      .el-input {
        width: 21%;
      }
      .el-button {
        width: 120px;
      }
    }
  }
}
</style>
